package com.zhangxiaofanfan.hotcode.third;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked">字母异位词分组</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-20 22:59:42
 */
public class HotCode002 {
    public static void main(String[] args) {
        String[] strs = {"bur", "rub"};
        HotCode002 hotCode002 = new HotCode002();
        hotCode002.groupAnagrams(strs).forEach(System.out::println);
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            String format = format(str);
            if (!map.containsKey(format)) {
                map.put(format, new ArrayList<>());
            }
            map.get(format).add(str);
        }
        return new ArrayList<>(map.values());
    }

    public String format(String str) {
        int[] nums = new int[26];
        for (int i = 0; i < str.length(); i++) {
            int index = str.charAt(i) - 'a';
            nums[index]++;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                sb.append((char) ('a' + i)).append(nums[i]);
            }
        }
        return sb.toString();
    }
}
